﻿using System;
using System.Collections;
using System.Text;
using System.Data;
using GeneralLibs;
using System.Collections;
using System.Data.SqlClient;

namespace Lists.SOP
{
    public enum MainSOPState
    {
        Undefined = 0,
        CreatingNew,
        Modifying,
        SavedInLedger,

        //for danh muc       
        Saved,
    }

    public class MainSOP : DoiTuong
    {
        #region Guid LoaiSoSOPID property
        public Guid LoaiSoSOPID
        {
            get
            {
                if (_DataRow["LoaiSoSOPID"] is Guid) return (Guid)_DataRow["LoaiSoSOPID"];
                return Guid.Empty;
            }
            set
            {
                _DataRow["LoaiSoSOPID"] = value;
            }
        }
        #endregion

        #region Guid VatTuHangHoaID property
        public Guid VatTuHangHoaID
        {
            get
            {
                if (_DataRow["VatTuHangHoaID"] is Guid) return (Guid)_DataRow["VatTuHangHoaID"];
                return Guid.Empty;
            }
            set
            {
                _DataRow["VatTuHangHoaID"] = value;
            }
        }
        #endregion

        #region int Thang property
        public int Thang
        {
            get
            {
                if (_DataRow["Thang"] is int) return (int)_DataRow["Thang"];
                return 0;
            }
            set
            {
                _DataRow["Thang"] = value;
            }
        }
        #endregion

        #region int Nam property
        public int Nam
        {
            get
            {
                if (_DataRow["Nam"] is int) return (int)_DataRow["Nam"];
                return 0;
            }
            set
            {
                _DataRow["Nam"] = value;
            }
        }
        #endregion

        #region State property
        public MainSOPState State
        {
            get
            {
                try
                {
                    SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
                    try
                    {
                        con.Open();
                        SqlCommand cmd = con.CreateCommand();
                        cmd.CommandText = string.Format("SELECT State, LastEditByUserID FROM MainSOP WHERE ID = '{0}'", this.ID);
                        SqlDataReader dr = cmd.ExecuteReader();
                        if (dr.Read())
                        {
                            DataRow["State"] = dr["State"];
                            DataRow["LastEditByUserID"] = dr["LastEditByUserID"];
                        }
                        dr.Close();

                        if (DataRow["State"] is byte)
                            return (MainSOPState)(byte)DataRow["State"];
                        else
                            return MainSOPState.Undefined;
                    }
                    catch (SqlException sqlEx)
                    {
                        throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
                    }
                    catch (Exception ex)
                    {
                        return MainSOPState.Undefined;
                    }
                    finally
                    {
                        con.Close();
                    }
                }
                catch
                {
                    return MainSOPState.Undefined;
                }
            }
            set
            {
                SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    if (CustomSecurity.User.CurUser.UserName != "SupAdmin")
                    {
                        cmd.CommandText = string.Format("UPDATE MainSOP Set State = {0}, LastEditByUserID = '{1}' WHERE ID = '{2}'",
                                        (byte)value, CustomSecurity.User.CurUser.ID, this.ID);
                    }
                    else
                    {
                        cmd.CommandText = string.Format("UPDATE MainSOP Set State = {0} WHERE ID = '{2}'",
                                                                (byte)value, CustomSecurity.User.CurUser.ID, this.ID);
                    }
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Clear();
                    cmd.ExecuteNonQuery();

                    DataRow["State"] = (byte)value;
                }
                catch (SqlException sqlEx)
                {
                    throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
                }
                finally
                {
                    con.Close();
                }
            }
        }
        #endregion

        #region LastEditByUserID property
        public Guid LastEditByUserID
        {
            get
            {
                if (DataRow["LastEditByUserID"] is Guid)
                    return (Guid)DataRow["LastEditByUserID"];
                else
                    return Guid.Empty;
            }
            set
            {
                DataRow["LastEditByUserID"] = value;
            }
        }
        #endregion

        #region int SoLanKhongDamBaoNhietDo property
        public int SoLanKhongDamBaoNhietDo
        {
            get
            {
                if (_DataRow["SoLanKhongDamBaoNhietDo"] is int) return (int)_DataRow["SoLanKhongDamBaoNhietDo"];
                return 0;
            }
            set
            {
                _DataRow["SoLanKhongDamBaoNhietDo"] = value;
            }
        }
        #endregion

        #region string LyDoKhongDamBaoNhietDo property
        public string LyDoKhongDamBaoNhietDo
        {
            get
            {
                if (_DataRow["LyDoKhongDamBaoNhietDo"] is string) return (string)_DataRow["LyDoKhongDamBaoNhietDo"];
                return "";
            }
            set
            {
                _DataRow["LyDoKhongDamBaoNhietDo"] = value;
            }
        }
        #endregion

        #region int SoLanKhongDamBaoDoAm property
        public int SoLanKhongDamBaoDoAm
        {
            get
            {
                if (_DataRow["SoLanKhongDamBaoDoAm"] is int) return (int)_DataRow["SoLanKhongDamBaoDoAm"];
                return 0;
            }
            set
            {
                _DataRow["SoLanKhongDamBaoDoAm"] = value;
            }
        }
        #endregion

        #region string LyDoKhongDamBaoDoAm property
        public string LyDoKhongDamBaoDoAm
        {
            get
            {
                if (_DataRow["LyDoKhongDamBaoDoAm"] is string) return (string)_DataRow["LyDoKhongDamBaoDoAm"];
                return "";
            }
            set
            {
                _DataRow["LyDoKhongDamBaoDoAm"] = value;
            }
        }
        #endregion

        public MainSOP(DataRow dataRow)
            : base(dataRow)
        {
        }

        public void CheckBeingEditedByOtherUser()
        {
            if (this.State == MainSOPState.Modifying && this.LastEditByUserID is Guid && this.LastEditByUserID != Guid.Empty &&
                this.LastEditByUserID != CustomSecurity.User.CurUser.ID && CustomSecurity.User.CurUser.UserName != "SupAdmin")
            {
                string message = string.Format("SOP này đang được sửa bởi {0}", CustomSecurity.UserList.Instance.GetByID(this.LastEditByUserID).UserName);
                throw new CustomException(message, ExceptionType.GeneralUserError);
            }
        }
    }

    public class DanhMucMainSOP : DanhMucDoiTuong, IEnumerable
    {
        #region Instance property: Singleton Design pattern
        private static DanhMucMainSOP _Instance;
        public static DanhMucMainSOP Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new DanhMucMainSOP();
                    //UniqueConstraint uniqueConstraint = new UniqueConstraint(_Instance.DataTable.Columns["Ma"]);
                    //_Instance.DataTable.Constraints.Add(uniqueConstraint);
                    //_Instance.DataView = _Instance.DataTable.DefaultView;
                    //_Instance.DataView.Sort = "Ma";
                }
                return _Instance;
            }
        }
        #endregion

        #region override TableName property
        public override string TableName
        {
            get
            {
                return "MainSOP";
            }
        }
        #endregion

        #region Methods required by IEnumerable (use for foreach)
        public IEnumerator GetEnumerator()
        {
            return new TokenEnumerator(this);
        }

        private class TokenEnumerator : IEnumerator
        {
            private int _Position = -1;
            DanhMucDoiTuong _Dstk;

            public TokenEnumerator(DanhMucDoiTuong dstk)
            {
                _Dstk = dstk;
            }

            // Declare the MoveNext method required by IEnumerator:
            public bool MoveNext()
            {
                if (_Position < _Dstk.DataView.Count - 1)
                {
                    _Position++;
                    return true;
                }
                else
                {
                    return false;
                }
            }

            // Declare the Reset method required by IEnumerator:
            public void Reset()
            {
                _Position = -1;
            }

            // Declare the Current property required by IEnumerator:
            public object Current
            {
                get
                {
                    return new MainSOP((_Dstk.DataView[_Position].Row));
                }
            }
        }
        #endregion

        public MainSOP this[int index]
        {
            get
            {
                if (0 <= index && index <= this.Count)
                {
                    if (DataView.Count > 0)
                        return new MainSOP(DataView.ToTable().Rows[index]);
                    else
                        return new MainSOP(DataTable.Rows[index]);
                }
                else
                {
                    return null;
                }
            }
        }

        public MainSOP NewDoiTuong()
        {
            return new MainSOP(DataTable.NewRow());
        }

        public MainSOP GetByProperty(string property, object value)
        {
            try
            {
                DataRow[] rows = GetDataRows(property, value);
                if (rows.Length > 0) return new MainSOP(rows[0]);
                else return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public MainSOP GetByID(Guid MainSOPID)
        {
            return GetByProperty("ID", MainSOPID);
        }
        public MainSOP GetByMa(string ma)
        {
            try
            {
                DataRow[] rows = DataTable.Select(string.Format("Ma = '{0}'", ma));
                if (rows.Length > 0)
                    return new MainSOP(rows[0]);
                else return null;
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        public static DanhMucMainSOP GetAll()
        {
            return Instance;
        }
        public DanhMucMainSOP GetByLoaiSoSOPID(Guid loaiSoSOPID)
        {
            return Filter(string.Format("LoaiSoSOPID = '{0}'", loaiSoSOPID));
        }

        public DanhMucMainSOP GetByLoaiSoSOPID_VatTuHangHoaID(Guid loaiSoSOPID, Guid vthhID)
        {
            string filterExpresstion = string.Format("LoaiSoSOPID = '{0}' AND VatTuHangHoaID = '{1}'", loaiSoSOPID, vthhID);
            return Filter(filterExpresstion);
        }

        public DanhMucMainSOP GetByLoaiSoSOPID_VatTuHangHoaID(Guid loaiSoSOPID, int thang, int nam)
        {
            string filterExpresstion = string.Format("LoaiSoSOPID = '{0}' AND Thang = {1} AND Nam = {2}", loaiSoSOPID, thang, nam);
            return Filter(filterExpresstion);
        }

        public static DanhMucMainSOP Filter(string filterExpression)
        {
            try
            {
                DanhMucMainSOP obj = new DanhMucMainSOP();
                obj.DataView = new DataView(DanhMucMainSOP.Instance.DataTable, filterExpression, "", DataViewRowState.CurrentRows);
                return obj;
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }
    }
}
